<template>
  <div>
    <el-form ref="pram" :model="pram" :rules="rules" label-width="100px" @submit.native.prevent>
      <el-form-item label="名称" prop="name">
        <el-input v-model="pram.name" maxlength="150" placeholder="名称" />
      </el-form-item>
      <el-form-item label="图片" prop="url">
        <el-tooltip
          class="item"
          effect="dark"
          content="上传图片"
          placement="top-start"
        >
          <el-upload
            class="upload-demo"
            action
            accept="image/gif,image/jpeg,image/png"
            :before-upload="onBeforeUpload"
            :http-request="handleUploadForm"
            :on-change="imgSaveToUrl"
            :headers="myHeaders"
            :show-file-list="false"
          >
            <el-button
              icon="el-icon-plus"
              class="mr15 definedArea"
              style="width:300px;height:150px;"
            ></el-button>
          </el-upload>
        </el-tooltip>
        <div v-if="this.dialogImageUrl">
          <el-button
            icon="el-icon-close"
            class="imgDel"
            @click.native="handlerImgDel"
          ></el-button>
          <img width="100%" :src="this.dialogImageUrl" alt="" class="img-box">
        </div>
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="pram.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="pram.sort" :min="0"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSubmit('pram')" v-hasPermi="['admin:swiper:update','admin:swiper:save']">{{ isCreate===0?'确定':'更新' }}</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import * as swiperApi from '@/api/swiper.js'
import * as systemSetting from '@/api/systemSetting.js'
import {getToken} from "@/utils/auth";
import {Debounce} from '@/utils/validate'
export default {
  // name: "edit"
  components: { },
  props: {
    isCreate: {
      type: Number,
      required: true
    },
    editData: {
      type: Object,
      default: () => {
        return { rules: [] }
      }
    },
  },
  data() {
    return {
      constants:this.$constants,
      pram: {
        name: null,
        url:null,
        sort: 0,
        status:1,
        id: 0,
      },
      rules: {
        name: [{ required: true, message: '请填名称', trigger: ['blur', 'change'] }],
        url: [{ required: true, message: '请上传图片', trigger: ['blur', 'change'] }],
      },
      myHeaders: { "X-Token": getToken() },
      localFile: null,
      dialogImageUrl: null,
    }
  },
  mounted() {
    this.initEditData()
  },
  methods: {
    close() {
      this.$emit('hideEditDialog')
    },
    //图片上传有关
    onBeforeUpload(file) {
      const isIMAGE = file.type === 'image/jpg'||'image/gif'||'image/png';
      const isLt1M = file.size / 1024 / 1024 < 10;

      if (!isIMAGE) {
        this.$message.error('上传文件只能是jpg、png或gif格式!');
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
      return isIMAGE && isLt1M;
    },
    // 上传
    handleUploadForm(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      systemSetting.fileImageApi(formData).then((res) => {
        //图片上传接口 后期调用
        this.pram.url = res

        loading.close();
        this.$message.success("上传成功");
        })
      .catch((res) => {
        loading.close();
      });
    },
    // 选取图片后自动回调，里面可以获取到文件
    imgSaveToUrl(event) {
      // 也可以用file
      this.localFile = event.raw; // 或者 this.localFile=file.raw

      // 转换操作可以不放到这个函数里面，
      // 因为这个函数会被多次触发，上传时触发，上传成功也触发
      let reader = new FileReader();
      reader.readAsDataURL(this.localFile); // 这里也可以直接写参数event.raw

      // 转换成功后的操作，reader.result即为转换后的DataURL ，
      // 它不需要自己定义，你可以console.integralLog(reader.result)看一下
      reader.onload = () => {
        //console.integralLog(reader.result)
      };

      /* 另外一种本地预览方法 */

      let URL = window.URL || window.webkitURL;
      this.dialogImageUrl = URL.createObjectURL(event.raw);
      // 转换后的地址为 blob:http://xxx/7bf54338-74bb-47b9-9a7f-7a7093c716b5
    },
    handlerImgDel(){
      this.pram.url = null
      this.dialogImageUrl = null
    },

    initEditData() {
      this.typeList = this.allTypeList

      if (this.isCreate !== 1) return //编辑
      const { name, url, sort, status, id } = this.editData //通过list中slot-scope=“scope“，scope.$index就是该行的下标，scope.row就是该行的数据所有消息对象，有了这两个参数就可以实现编辑、删除功能（this.editData就是scope.row传入的对象参数）
      this.pram.name = name
      this.pram.status = status
      this.pram.sort = sort
      this.pram.url = url
      this.dialogImageUrl = url
      this.pram.id = id
    },

    handlerSubmit:Debounce(function(form) {
      this.$refs[form].validate(valid => {
        if (!valid) return
        if (this.isCreate === 0) {
          this.handlerSave()
        } else {
          this.handlerEdit()
        }
      })
    }),
    handlerSave() {
      swiperApi.picAdd(this.pram).then(data => {
        this.$message.success('创建轮播图成功')
        this.$emit('hideEditDialog')
      })
    },
    handlerEdit() {
      swiperApi.picAdd(this.pram).then(data => {
        this.$message.success('更新轮播图成功')
        this.$emit('hideEditDialog')
      })
    },
  }
}
</script>

<style scoped lang="scss">
.imgDel{
  position: absolute;
  z-index: 4;
  top: 1px;
  border: 0;
  width: 15px!important;
  height: 15px!important;
  text-align: center;
  //right: -1px;
  left:284px;
  padding: 0px!important;
  line-height: 10px!important;
  border-radius: 0!important;
  font-weight:bold;
}
.img-box{
  position:absolute;
  z-index: 3;
  top:0;
  width: 300px;
  height: 150px;
  border:0;
}
</style>
